package com.gigi.datageniebackendmaster.aop;

import com.gigi.datageniebackendmaster.annotation.AuthCheck;
import com.gigi.datageniebackendmaster.common.Constant;
import com.gigi.datageniebackendmaster.util.AuthorityUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 鉴权拦截器
 * <p>
 * 使用 @AuthCheck注解，不传参数，默认 checkType 鉴权类型为 “是否登录” ，一般用于 查询、搜索、详情 接口
 * 传参数 checkType 为 "isAdmin"，鉴权类型为 “是否管理员” ，一般用于 管理员操作 接口
 *
 * @author Gigi
 * @date 2024/8/28 14:58
 */
@Aspect
@Component
public class AuthInterceptor {

    @Around("@annotation(authCheck)")
    public Object logInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest httpServletRequest = ((ServletRequestAttributes) requestAttributes).getRequest();
        String checkType = authCheck.checkType();
        if (Constant.IS_LOGIN.equals(checkType)) {
            AuthorityUtil.getLoginUser(httpServletRequest);
        }
        if (Constant.IS_ADMIN.equals(checkType)) {
            AuthorityUtil.isAdmin(httpServletRequest);
        }
        return joinPoint.proceed();
    }

}
